<?php
abstract class ContentFile
{
	abstract public function readContent( $oResponse, $sAbsolutePath );
}

class ContentDispatcher
{
	/**
	 * @param ServerResponse $oResponse
	 * @param String $sAbsolutePath
	 */
	public function readContent( $oResponse, $sRelativePath )
	{
		require_once( 'url.php' );
		$sAbsolutePath = '../'.Url::getContentUrl( $sRelativePath );
		if ( !file_exists( $sAbsolutePath ) )
		{
			$oResponse->error( 'The file \''.$sRelativePath.'\' does not exist');
			return;
		}
		if ( !is_readable( $sAbsolutePath ) )
		{
			$oResponse->error( 'The file \''.$sRelativePath.'\' is not readable');
			return;
		}
		$oContentFile = $this->getContentFile( $oResponse, $sRelativePath );
		if ( $oContentFile != null )
		{
			$oContentFile->readContent( $oResponse, $sAbsolutePath );
		}
		else
		{
			$oResponse->error( 'Cannot get the corresponding content file object from the file' );
			return;
		}
		$oResponse->requestExecuted();
	}
	
	/**
	 * Return a ContentFile object corresponding to the file type
	 *
	 * @param ServerResponse $oResponse
	 * @param String $sRelativePath
	 * @return ContentFile
	 */
	private function getContentFile( $oResponse, $sPath )
	{
		require_once( 'config.php' );
		require_once( 'io.php' );
		$sFileExtension = FileManager::getLongFileExtension( $sPath );
		$oContentFile = null;
		
		$bFound = false;
		assert( isset( $_SESSION[ 'oFileFormats' ] ) );
		foreach ( $_SESSION[ 'oFileFormats' ] as $sKey => $oPair )
		{
			$sPattern = '`^'.$sKey.'$`i';
			if ( preg_match( $sPattern, $sFileExtension ) )
			{
				require_once( $oPair[ 0 ] );
				$oContentFile = new $oPair[ 1 ];
				$bFound = true;
				break;
			}
		}
		
		if ( !$bFound )
		{
			if ( FileManager::getFileExtension( $sFileExtension ) == 'xml' )
			{
				$oResponse->warning( 'unknown file extension \''.$sFileExtension.'\', showing as xml' );
				require_once( 'xml_viewer.php' );
				$oContentFile = new XmlViewer();
			}
			else 
			{
				$oResponse->warning( 'unknown file extension \''.$sFileExtension.'\', showing as text' );
				require_once( 'txt_viewer.php' );
				$oContentFile = new TxtViewer();
			}
		}
		
		return $oContentFile;
	}
}
?>